<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>法律问答系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }
        
        .main-content {
            padding: 40px;
        }
        
        .query-section {
            margin-bottom: 40px;
        }
        
        .query-form {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .query-input {
            flex: 1;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        .query-input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .query-btn {
            padding: 15px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            cursor: pointer;
            transition: transform 0.2s;
        }
        
        .query-btn:hover {
            transform: translateY(-2px);
        }
        
        .query-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        
        .result-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            margin-top: 20px;
        }
        
        .answer {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #667eea;
        }
        
        .answer h3 {
            color: #2c3e50;
            margin-bottom: 15px;
        }
        
        .answer-content {
            line-height: 1.6;
            color: #333;
        }
        
        .metadata {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
            font-size: 14px;
            color: #666;
        }
        
        .metadata span {
            background: #e9ecef;
            padding: 5px 10px;
            border-radius: 15px;
        }
        
        .sources {
            margin-top: 20px;
        }
        
        .sources h4 {
            color: #2c3e50;
            margin-bottom: 15px;
        }
        
        .source-item {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 10px;
            border: 1px solid #e0e0e0;
        }
        
        .source-title {
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 5px;
        }
        
        .source-content {
            color: #666;
            font-size: 14px;
            line-height: 1.5;
        }
        
        .source-meta {
            margin-top: 10px;
            font-size: 12px;
            color: #999;
        }
        
        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #f5c6cb;
        }
        
        .upload-section {
            border-top: 1px solid #e0e0e0;
            padding-top: 40px;
            margin-top: 40px;
        }
        
        .upload-form {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .form-input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
        }
        
        .file-input {
            border: 2px dashed #ccc;
            padding: 20px;
            text-align: center;
            border-radius: 8px;
            cursor: pointer;
            transition: border-color 0.3s;
        }
        
        .file-input:hover {
            border-color: #667eea;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>⚖️ 法律问答系统</h1>
            <p>基于AI的智能法律咨询助手</p>
        </div>
        
        <div class="main-content">
            <!-- 查询部分 -->
            <div class="query-section">
                <h2>💬 法律咨询</h2>
                <div class="query-form">
                    <input type="text" id="questionInput" class="query-input" 
                           placeholder="请输入您的法律问题，例如：民法典的立法目的是什么？">
                    <button id="queryBtn" class="query-btn">查询</button>
                </div>
                
                <div id="loadingDiv" class="loading" style="display: none;">
                    🔍 正在查询相关法律条文...
                </div>
                
                <div id="resultDiv" style="display: none;"></div>
            </div>
            
            <!-- 文档上传部分 -->
            <div class="upload-section">
                <h2>📄 文档上传</h2>
                <div class="upload-form">
                    <div class="form-group">
                        <label class="form-label">选择文档文件</label>
                        <input type="file" id="fileInput" class="form-input" 
                               accept=".pdf,.docx,.txt">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">文档标题</label>
                        <input type="text" id="titleInput" class="form-input" 
                               placeholder="请输入文档标题">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">法律分类</label>
                        <select id="categoryInput" class="form-input">
                            <option value="">请选择分类</option>
                            <option value="民法">民法</option>
                            <option value="刑法">刑法</option>
                            <option value="行政法">行政法</option>
                            <option value="商法">商法</option>
                            <option value="劳动法">劳动法</option>
                            <option value="知识产权法">知识产权法</option>
                            <option value="环境法">环境法</option>
                            <option value="税法">税法</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">文档来源</label>
                        <input type="text" id="sourceInput" class="form-input" 
                               placeholder="例如：最高人民法院、全国人大常委会">
                    </div>
                    
                    <button id="uploadBtn" class="query-btn">上传文档</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = '/api/v1';
        
        // 查询功能
        document.getElementById('queryBtn').addEventListener('click', async () => {
            const question = document.getElementById('questionInput').value.trim();
            if (!question) {
                alert('请输入问题');
                return;
            }
            
            const queryBtn = document.getElementById('queryBtn');
            const loadingDiv = document.getElementById('loadingDiv');
            const resultDiv = document.getElementById('resultDiv');
            
            // 显示加载状态
            queryBtn.disabled = true;
            queryBtn.textContent = '查询中...';
            loadingDiv.style.display = 'block';
            resultDiv.style.display = 'none';
            
            try {
                const response = await fetch(`${API_BASE}/query`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        question: question,
                        user_id: 'web_user',
                        top_k: 5
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const data = await response.json();
                displayResult(data);
                
            } catch (error) {
                console.error('查询失败:', error);
                resultDiv.innerHTML = `
                    <div class="error">
                        查询失败: ${error.message}
                    </div>
                `;
                resultDiv.style.display = 'block';
            } finally {
                queryBtn.disabled = false;
                queryBtn.textContent = '查询';
                loadingDiv.style.display = 'none';
            }
        });
        
        // 显示查询结果
        function displayResult(data) {
            const resultDiv = document.getElementById('resultDiv');
            
            const html = `
                <div class="result-section">
                    <div class="answer">
                        <h3>📋 回答</h3>
                        <div class="answer-content">${data.answer}</div>
                    </div>
                    
                    <div class="metadata">
                        <span>置信度: ${(data.confidence_score * 100).toFixed(1)}%</span>
                        <span>响应时间: ${data.response_time.toFixed(2)}秒</span>
                        <span>相关文档: ${data.retrieved_documents.length}个</span>
                    </div>
                    
                    ${data.retrieved_documents.length > 0 ? `
                        <div class="sources">
                            <h4>📚 参考文档</h4>
                            ${data.retrieved_documents.map(doc => `
                                <div class="source-item">
                                    <div class="source-title">${doc.title}</div>
                                    <div class="source-content">${doc.content}</div>
                                    <div class="source-meta">
                                        来源: ${doc.source || '未知'} | 
                                        分类: ${doc.category || '未分类'} | 
                                        相似度: ${(doc.score * 100).toFixed(1)}%
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    ` : ''}
                </div>
            `;
            
            resultDiv.innerHTML = html;
            resultDiv.style.display = 'block';
        }
        
        // 文档上传功能
        document.getElementById('uploadBtn').addEventListener('click', async () => {
            const fileInput = document.getElementById('fileInput');
            const titleInput = document.getElementById('titleInput');
            const categoryInput = document.getElementById('categoryInput');
            const sourceInput = document.getElementById('sourceInput');
            
            if (!fileInput.files[0]) {
                alert('请选择文件');
                return;
            }
            
            if (!titleInput.value.trim()) {
                alert('请输入文档标题');
                return;
            }
            
            const uploadBtn = document.getElementById('uploadBtn');
            uploadBtn.disabled = true;
            uploadBtn.textContent = '上传中...';
            
            try {
                const formData = new FormData();
                formData.append('file', fileInput.files[0]);
                formData.append('title', titleInput.value.trim());
                formData.append('category', categoryInput.value);
                formData.append('source', sourceInput.value.trim());
                
                const response = await fetch(`${API_BASE}/documents/upload`, {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const data = await response.json();
                alert(`文档上传成功！\n状态: ${data.status}\n消息: ${data.message}`);
                
                // 清空表单
                fileInput.value = '';
                titleInput.value = '';
                categoryInput.value = '';
                sourceInput.value = '';
                
            } catch (error) {
                console.error('上传失败:', error);
                alert(`上传失败: ${error.message}`);
            } finally {
                uploadBtn.disabled = false;
                uploadBtn.textContent = '上传文档';
            }
        });
        
        // 回车键查询
        document.getElementById('questionInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                document.getElementById('queryBtn').click();
            }
        });
        
        // 示例问题
        const exampleQuestions = [
            "民法典的立法目的是什么？",
            "合同的基本原则有哪些？",
            "劳动合同应当遵循什么原则？",
            "什么是诚信原则？"
        ];
        
        // 随机显示示例问题
        function showExampleQuestion() {
            const randomQuestion = exampleQuestions[Math.floor(Math.random() * exampleQuestions.length)];
            document.getElementById('questionInput').placeholder = `例如：${randomQuestion}`;
        }
        
        // 页面加载完成后显示示例
        window.addEventListener('load', () => {
            showExampleQuestion();
            setInterval(showExampleQuestion, 5000); // 每5秒切换示例
        });
    </script>
</body>
</html>
